/* Copyright (c) 2004-2024 Peigen.info. All rights reserved. */

package info.peigen.hotpot.component.gateway.core.util;

import cn.hutool.core.util.HexUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;

/**
 * <b>(Cp56Time2aUtil)</b>
 *
 * @author Peigen
 * @version 1.0.0
 * @since 2022/9/2
 */
@Slf4j
public class Cp56Time2aUtil {

    public static int[] hexStringToIntArray(String hexStr) {
        String[] hexArray = StrUtil.split(hexStr, 2);
        return Arrays.stream(hexArray).mapToInt(HexUtil::hexToInt).toArray();
    }

    /**
     * 时标CP56Time2a解析
     *
     * @param hexStr 时标CP56Time2a
     *
     * @return 解析结果
     */
    public static String decode(String hexStr) {
        int[] b      = hexStringToIntArray(hexStr);
        int   year   = b[6] & 0x7F;
        int   month  = b[5] & 0x0F;
        int   day    = b[4] & 0x1F;
        int   week   = (b[4] & 0xE0) / 32;
        int   hour   = b[3] & 0x1F;
        int   minute = b[2] & 0x3F;
        int   second = (b[1] << 8) + b[0];

        return year + 2000 + "-" +
                String.format("%02d", month) + "-" +
                String.format("%02d", day) + " " +
                hour + ":" + minute + ":" +
                second / 1000;
    }

    /**
     * 时间转16进制字符串
     *
     * @param date Date
     *
     * @return 解析结果
     */
    public static String encode(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        StringBuilder builder     = new StringBuilder();
        String        milliSecond = String.format("%04X", (calendar.get(Calendar.SECOND) * 1000) + calendar.get(Calendar.MILLISECOND));
        builder.append(milliSecond, 2, 4);
        builder.append(milliSecond, 0, 2);
        builder.append(String.format("%02X", calendar.get(Calendar.MINUTE) & 0x3F));
        builder.append(String.format("%02X", calendar.get(Calendar.HOUR_OF_DAY) & 0x1F));
        int week = calendar.get(Calendar.DAY_OF_WEEK);
        if (week == Calendar.SUNDAY) {
            week = 7;
        } else {
            week--;
        }
        builder.append(String.format("%02X", (calendar.get(Calendar.DAY_OF_MONTH) & 0x1F)));
        builder.append(String.format("%02X", calendar.get(Calendar.MONTH) + 1));
        builder.append(String.format("%02X", calendar.get(Calendar.YEAR) - 2000));
        return builder.toString();
    }
}
